package ops.view.component;

import java.awt.Toolkit;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;


/**
 * A {@link JTextField} that only accepts chars as valid input and
 * also has a limited input range.
 * Default size is 10.
 * @author flavio
 */
public class StringField extends LimitedSizeField {

	public StringField() {
		this(10);
	}
	
	public StringField(String str) {
		this(str, str.length());
	}
	
	public StringField(int size) {
		this("", size);
	}
	
	public StringField(String str, int size) {
		this(new StringDocument(size), str, size);
	}
	
	protected StringField(LimitedSizeDocument doc, String obj, int size) {
		super(doc, obj, size);
	}
	
	private static class StringDocument extends LimitedSizeDocument {
		
		public StringDocument(int size) {
			super(size);
		}
		
		@Override
		public void insertString(int offset, String str, AttributeSet attr)
				throws BadLocationException {
			
			if (str == null || str.equals("")) 
				return;
			
			for (int i = str.length()-1; i > -1; i--) {
				Character ch = str.charAt(i);
				if (Character.isLetter(ch)) {
					super.insertString(offset, ch.toString(), attr);
				} else {
					Toolkit.getDefaultToolkit().beep();
				}
			}
		}		
	}

}
